import socket,time

class Protocol():
    # 模拟ip协议通信过程
    def TCP(self):
        for i in range(1,6):
            mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 实例化socket对象
            mysocket.connect(('192.168.2.196', 554))   #建立连接——三次握手
            msg = 'sdgf第一轮，第' + str(i) + '次，这是消息的内容'
            mysocket.send(msg.encode("gb2312"))    #发送消息
            mysocket.close()    #断开连接——四次挥手
            time.sleep(2)

    # 模拟udp协议通信过程
    def UDP(self):
        for i in range(1,6):
            mysocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)   # 实例化socket对象
            mysocket.connect(("192.168.2.145",778))   #建立连接
            # IPMSG的报文格式：版本号：包编号：发送者姓名：发送者主机名：命令字：附加信息
            version = "1.1"  #只允许2.0以下的版本
            packetId = str(time.time())
            name = 'CC sensei'
            host = 'CC sensei'
            command = str(0x00000020)
            content = 'This is the message from python'
            msg = version+':'+packetId+':'+name+':'+host+':'+command+':'+content
            mysocket.send(msg.encode('GBK'))    #发送消息
            mysocket.close()   #断开连接

if __name__ == '__main__':
    p = Protocol()
    # p.TCP()
    p.UDP()
